// import { login, logout, getInfo, getMenus, getCheckName } from '@/api/login' // 远程菜单
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, initConf } from '@/utils/auth'
// 导入-模拟菜单
import { menus } from '@/utils/menus'

const user = {
  state: {
    token: getToken(),
    name: '',
    info: '',
    roles: '',
    currMenu: null, // 当前菜单对象
    menus: [] // 远程菜单
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_CURRMENU: (state, obj) => { // 设置菜单 - 当前
      state.currMenu = obj
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.type, userInfo.deviceId, userInfo.channelId).then(response => {
          if (response.status == 0) {
            setToken(response.data)
            commit('SET_TOKEN', response.data)
            // commit('SET_MENUS', menus)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息 --获取菜单
    GetInfo({ commit, state }, to) {
      // 获取用户信息
      return new Promise((resolve, reject) => {
        // 获取动态配置
        initConf().then(() => {
          getInfo(state.token).then(response => {
            const user = response.data
            // user.agent = data.agent // 代理信息
            // user.authMenu = data.authMenu // 系统用户(独立菜单权限)
            commit('SET_ROLES', 'Merchant')
            commit('SET_NAME', user.name)
            commit('SET_INFO', user)
            // 获取-模拟菜单
            commit('SET_MENUS', menus)
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        }).catch((err) => { reject(err) })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', '')
          removeToken()
          sessionStorage.clear() // 清除缓存--state
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
